<?php

use \Mapper\SparringGameModel as SparringGameMapper;

class SparringgameController extends \Base\AbstractController {

    /**
     * @desc 列表页
     */
    public function listAction() {
        $page = new \Lib\Paginator('sparringGame');
        $this->assign('count', $page->count());
        $this->assign('page', $page->getPage());
        $this->assign('perPage', $page->getPerpage());
        $this->assign('lists', $page->lists());

    }

    /**
     * @desc 添加
     */
    public function addAction() {
        $request  = $this->getRequest();
        $gameName = trim((string)$request->get('game_name'));
        $order    = (int)$request->get('order');
        $status   = (int)$request->get('status');
        $model    = new \SparringGameModel();

        if($request->isPost()) {
            $model  = new \SparringGameModel();
            $mapper = SparringGameMapper::getInstance();
            $model->setGame_name($gameName);
            $model->setOrder($order);
            $model->setStatus($status);
            $model->setAdd_time(time());
            $count = $mapper->count(['status' => 1]);

            if($count > 14) {
                return \Response::errmsg('已经有15个了！');
            }

            try {
                $mapper->insert($model);
                return \Response::msg('添加成功！');
            } catch(Exception $exc) {
                return \Response::errmsg();

            }
        }

        $this->assign('model', $model);
        $this->display('edit');
        return false;

    }

    /**
     * @desc 编辑
     */
    public function editAction() {
        $request  = $this->getRequest();
        $id       = (int)$request->get('id');
        $gameName = trim((string)$request->get('game_name'));
        $order    = (int)$request->get('order');
        $status   = (int)$request->get('status');

        $mapper = SparringGameMapper::getInstance();
        $model  = $mapper->findById($id);

        if(!$model instanceof \SparringGameModel) {
            return false;
        }

        if($request->isPost()) {
            $model->setGame_name($gameName);
            $model->setOrder($order);
            $model->setStatus($status);
            $model->setUpdate_time(time());

            try {
                $rows = $mapper->update($model, ['id' => $id]);
                return $rows > 0 ? \Response::msg('修改成功!') : \Response::errmsg('信息未改动!');
            } catch(Exception $exc) {
                return \Response::errmsg($exc);
            }
        }

        $this->assign('model', $model);
    }

    /**
     * @desc 删除
     */
    public function delAction() {
        $request = $this->getRequest();
        $id      = $request->get('id');
        $mapper  = SparringGameMapper::getInstance();

        try {
            $mapper->del(['id' => $id]);
            return \Response::msg('删除成功！');
        } catch(Exception $exc) {
            return \Response::errmsg($exc->getMessage());
        }
    }
}
